import dayjs from 'dayjs'
import { defineStore } from 'pinia'

export const useArticleStore = defineStore(
  'article',
  () => {
    const articles = ref<
      {
        id: string
        title: string
        publishTime: string
        content: string
        classify: string
        views: number
        coverImage: string
        support: number
      }[]
    >([])

    // 生成唯一 id 的函数
    const generateId = () => {
      return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`
    }


    // 添加文章方法
    const addArticle = (
      title: string,
      content: string,
      classify: string,
      coverImage: string,
    ) => {
      const publishTimeISO = new Date().toISOString()
      const publishTime = dayjs(publishTimeISO).format('YYYY-MM-DD')
      articles.value.unshift({
        id: generateId(),
        title,
        publishTime,
        content,
        classify,
        views: 0,
        coverImage,
        support: 0,
      })
    }

    // 获取所有文章
    const getArticles = () => {
      return articles.value
    }

    
    // 根据文章id获取文章
    const getArticleById = (id: string) => {
      return articles.value.find(item => item.id === id)
    }

    // 增加浏览量
    const increaseViewCount = (id: string) => {
      const article = getArticleById(id)
      if (article) {
        article.views += 1
      }
    }

    // 记录每篇文章的点赞状态 (使用 Array 来存储已点赞文章ID)
    const likedArticles = ref<string[]>([])

    // 增加点赞数量
    const increaseSupport = (id: string) => {
      const article = getArticleById(id)
      if (article) {
        const index = likedArticles.value.indexOf(id)
        if (index === -1) {
          // 如果没有点赞，增加点赞
          likedArticles.value.push(id)
          article.support += 1
        } else {
          // 如果已经点赞，取消点赞
          likedArticles.value.splice(index, 1)
          article.support -= 1
        }
      }
    }



    return {
      articles,
      addArticle,
      getArticles,
      increaseViewCount,
      likedArticles,
      increaseSupport,
      getArticleById
    }
  },
  {
    persist: true,
  },
)
